package com.itlnn.xfeng.painviw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.hanvon.penenginejni.HWPenEngine;

import java.io.InputStream;

/**
 * 画笔的View类
 * @User :      xuyuqiang
 * @Date :      2017/3/16 下午2:01
 * @Version :   1.0.0
 * @ClassName : PainView2
 **/
public class PainView2 extends SurfaceView implements SurfaceHolder.Callback {

    //笔锋的默认宽度
    private static final int PIAN_DEFWIDTH = 8 ;
    //笔锋的默认样式  PEN
    private static final int PIAN_DEFTYPE = 3 ;

    //Surface的控制类
    private SurfaceHolder mSurfaceHolder ;
    //画笔迹的Bitmap
    private Bitmap mPaintSurface ;
    private Canvas mPaintCanvas ;

    private Paint mPaint ;

    //绘画修改的区域
    int [] rectUpdate ;

    //颜色处理
    private int [] mPixels ;

    //关联绘画核心的标记
    private long penEngine ;
    //标记手指触屏的状态
    private boolean mIsDown ;

    public PainView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mSurfaceHolder = this.getHolder() ;
        this.mSurfaceHolder.addCallback(this);
        this.setFocusable(true);
    }


    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

        if (mPaintSurface == null){
            init();
        }else{
            update();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    /**
     * 初始化必要属性
     * @Date 2017/3/20 下午3:16
     */
    private void init(){
        //初始化画布背景，是一个bitmap
//        this.mPaintSurface = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
        this.mPaintSurface = zoomBitmap(getContext() , this.getWidth() , this.getHeight() , R.drawable.body_bg2) ;
        //表示画布矩形的4个点
        this.rectUpdate = new int[4] ;
        //初始化画笔
        this.mPaint = new Paint() ;
        //存放当前色值的数组
        this.mPixels = new int[this.getWidth()* this.getHeight()] ;

        mPaintSurface.getPixels(mPixels , 0 , this.getWidth() , 0 , 0 , this.getWidth() , this.getHeight());
        mPaintCanvas = new Canvas(mPaintSurface) ;
        //与绘画核心进行关联
        this.penEngine = HWPenEngine.initialize(this.getWidth() , this.getHeight() , mPixels) ;
        //初始化笔的默认样式
        HWPenEngine.setPenStyle(penEngine , PIAN_DEFTYPE);
        //初始化笔的默认粗细
        HWPenEngine.setSize(penEngine , PIAN_DEFWIDTH);

        update();
    }

    /**
     * 更新画布
     * @Date 2017/3/20 下午3:33
     */ 
    public void update(Rect rect){
        if (rect != null && !rect.isEmpty()) {
            try {
                mPaintSurface.setPixels(mPixels, rect.top * this.getWidth() + rect.left, this.getWidth(), rect.left, rect.top, rect.width(), rect.height());
                Canvas canvas = mSurfaceHolder.lockCanvas(rect);
                drawLayers(canvas);
                mSurfaceHolder.unlockCanvasAndPost(canvas);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void update(){
        Rect rect = new Rect(0 , 0 , this.getWidth() , this.getHeight()) ;
        update(rect);
    }


    /**
     * 图层绘制
     * @Date 2017/3/20 下午3:31
     */
    private void drawLayers(Canvas canvas){
        if (canvas != null){
            canvas.drawColor(Color.WHITE);
            mPaint.setAlpha(255);
            canvas.drawBitmap(mPaintSurface , 0, 0 , mPaint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Point pf = new Point((int)event.getX() , (int)event.getY()) ;
        //设置触屏压力的大小为1.0F
        float pressure = 1.0f ;

        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_FINGER) {
            pressure = 1.0f;
        } else if (event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS) {
            pressure = event.getPressure();
        } else if (event.getToolType(0) == MotionEvent.TOOL_TYPE_ERASER) {
            pressure = event.getPressure();
        }

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if (!mIsDown){
                    mIsDown = true ;
                    HWPenEngine.beginStroke(penEngine);
                    HWPenEngine.strokePoint(penEngine , pf.x , pf.y , pressure , rectUpdate);
                    Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
                    trect.intersect(0, 0, this.getWidth(), this.getHeight());
                    //trect.union(touchedRect);
                    update(trect);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mIsDown){
                    HWPenEngine.strokePoint(penEngine , pf.x , pf.y , pressure , rectUpdate);
                    Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
                    trect.intersect(0, 0, this.getWidth(), this.getHeight());
                    //trect.union(touchedRect);
                    update(trect);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mIsDown){
                    mIsDown = false ;
                    HWPenEngine.endStroke(penEngine , rectUpdate);
                    Rect trect=new Rect(rectUpdate[0],rectUpdate[1],rectUpdate[2],rectUpdate[3]);
                    trect.intersect(0, 0, this.getWidth(), this.getHeight());
                    //trect.union(touchedRect);
                    update(trect);
                }
                break;
            default:
                break;
        }

        return true;
    }

    /**
     * 设置笔的颜色
     * @Date 2017/3/20 下午5:25
     */ 
    public void setPaintColor(byte b,byte g,byte r,byte a) {
        HWPenEngine.setColor(penEngine, b,g,r,a);
    }

    /**
     * 设置笔的粗细
     * @Date 2017/3/20 下午5:25
     */ 
    public void setPaintSize(int size){
        HWPenEngine.setSize(penEngine , size);
    }

    /**
     * 初始化默认白色的橡皮擦
     * @Date 2017/3/20 下午5:24
     */ 
    public void setStyle4Rubber(){
        setPaintColor((byte)255,(byte)255,(byte)255,(byte)0);
    }

    public Bitmap zoomBitmap(Context context , int width , int height  , int resId) {
        Bitmap bitmap = readBitMap(context , resId) ;
        float bWidth = bitmap.getWidth() ;
        float bHeight = bitmap.getHeight() ;
        Matrix matrix = new Matrix() ;
        float scaleWidth = (float)width / bWidth ;
        float scaleHeight = (float)height / bHeight ;
        matrix.postScale(scaleWidth , scaleHeight) ;
        Bitmap newBitmap = Bitmap.createBitmap(bitmap , 0 , 0 , (int)bWidth , (int)bHeight , matrix , true) ;
        bitmap.recycle();
        bitmap = null ;
        return newBitmap ;

    }

    /**
     * 以最省内存的方式读取本地资源的图片
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is,null,opt);
    }

}
